package servlet.stu;

import bean.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import dao.UserDaoImpl;
import utils.JwtUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;


//学生添加换房申请
@WebServlet("/stu/insertExchangeInfo")
public class InsertExchangeInfoServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String reason = request.getParameter("reason");
        String user_token = request.getHeader("user_token_header");
        Integer stuId= JwtUtils.getStuIdFromToken(user_token,"stuId");
        Integer dormitory= JwtUtils.getStuDormitoryFromToken(user_token,"dormitory");


        Integer newRoom = null;
        if (request.getParameter("newRoom") != null) {
            newRoom = Integer.valueOf(request.getParameter("newRoom"));
            System.out.println(newRoom);
        }
        Integer newBed = null;
        if (request.getParameter("newBed") != null) {
            newBed = Integer.valueOf(request.getParameter("newBed"));

        }
        Integer buildId = null;
        if (request.getParameter("buildId") != null) {
            buildId = Integer.valueOf(request.getParameter("buildId"));

        }
        Integer oldBuild= JwtUtils.getStuBuildIdFromToken(user_token,"buildId");

        String stuName= JwtUtils.getStuNameFromToken(user_token,"stuName");

        Integer data = null;
        try {
            data = UserDaoImpl.insertExchangeInfo(reason, stuId, dormitory, newRoom, newBed, oldBuild, buildId, stuName);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        Result result = new Result();
        if (data != null) {
            result.success(data);
            ObjectMapper objectMapper = new ObjectMapper();
            String str = objectMapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().print(str);


        } else {
            result.fail();
            ObjectMapper objectMapper = new ObjectMapper();
            String str = objectMapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().print(str);


        }
    }
}
